package com.zhilei.mq;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 延迟消息队列的生产者
 *
 * @author 志磊
 */
@Configuration
public class DelayConfig_Industry {

    public static final String EXCHANGE_DELAY_REFRESH = "exchange_delay_refresh";

    public static final String QUEUE_DELAY_REFRESH = "queue_delay_refresh";

    public static final String DELAY_REFRESH_INDUSTRY = "delay.refresh.industry";

    /**
     * 消息处理器，设置延迟消息时间
     *
     * @param times
     * @return
     */
    public static MessagePostProcessor setDelayTimes(Integer times) {
        return new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) {
                // TODO 设置持久属性，持久化
                message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);

                // TODO 设置持久时间，单位毫秒
                message.getMessageProperties().setDelay(times);
                return message;
            }
        };
    }

    // 声明一个交换机
    @Bean(EXCHANGE_DELAY_REFRESH)
    public Exchange exchange() {
        return ExchangeBuilder
                .topicExchange(EXCHANGE_DELAY_REFRESH)
                .durable(true)
                // TODO 开启延迟队列
                .delayed()
                .build();
    }

    // 声明一个队列
    @Bean(QUEUE_DELAY_REFRESH)
    public Queue queue() {
        return QueueBuilder
                .durable(QUEUE_DELAY_REFRESH)
                .build();
    }

    // 将队列和交换机绑定
    @Bean
    public Binding delayBindingIndustry(@Qualifier(EXCHANGE_DELAY_REFRESH) Exchange exchange,
                                        @Qualifier(QUEUE_DELAY_REFRESH) Queue queue) {
        return BindingBuilder
                .bind(queue)
                .to(exchange)
                .with("delay.refresh.*")
                .noargs();
    }
}
